package com.community.web.user.controller.cart;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.community.common.exception.NeusoftException;
import com.community.common.login.LoginUserHolder;
import com.community.common.result.Result;
import com.community.common.result.ResultCodeEnum;
import com.community.model.entity.Carts;
import com.community.web.user.service.CartsService;
import com.community.web.user.vo.CartInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "购物车模块")
@RestController
@RequestMapping("/user/carts")
public class CartsController {

    @Autowired
    private CartsService service;

    @ApiOperation("根据用户id查询购物车")
    @GetMapping()
    public Result<List<CartInfoVo>> cartList(){
        Long userId = LoginUserHolder.getLoginUser().getUserId();
        List<CartInfoVo> list = service.selectByUserId(userId);
        return Result.ok(list);
    }

    @ApiOperation("修改商品数量")
    @PutMapping()
    public Result update(@RequestBody Carts carts){
        Long userId = LoginUserHolder.getLoginUser().getUserId();
        carts.setUserId(userId.intValue());
        if (carts.getAmount() == 0){
            throw new NeusoftException(ResultCodeEnum.ZERO_ERROR);
        }
        service.updateNumber(carts);
        return Result.ok();
    }

    @ApiOperation("根据购物车id删除商品")
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Long id){
        service.removeById(id);
        return Result.ok();
    }

    @ApiOperation("根据用户id清空购物车")
    @DeleteMapping()
    public Result clear(){
        Long userId = LoginUserHolder.getLoginUser().getUserId();
        LambdaQueryWrapper<Carts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Carts::getUserId, userId);
        service.remove(queryWrapper);
        return Result.ok();
    }

    @ApiOperation("将商品加入购物车")
    @PostMapping()
    public Result add(@RequestBody Carts carts){
        if (carts.getAmount() == 0){
            throw new NeusoftException(ResultCodeEnum.ZERO_ERROR);
        }
        Long userId = LoginUserHolder.getLoginUser().getUserId();
        carts.setUserId(userId.intValue());
        service.add(carts);
        return Result.ok();
    }
}
